package thread.alternate_print;

/**
 * 核心是通过Thread.join()方法优先执行本线程
 *
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-08-02 23:30
 **/
public class ThreadJoinDemo {

    private int threadCount;
    private final int MAX = 100;
    private int count = 1;

    public ThreadJoinDemo(int threadCount) {
        this.threadCount = threadCount;
    }

    public void start() {
        Thread[] threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                if (count > MAX) return;
                System.out.println(Thread.currentThread().getName() + "-" + count++);
            }, "t" + (i + 1));
        }

        while (count <= MAX) {
            for (int i = 0; i < threadCount; i++) {
                if (count > MAX) return;
                try {
                    threads[i].start();
                    threads[i].join();
                    // 重新创建一个线程，开销巨大
                    threads[i] = new Thread(() -> {
                        if (count > MAX) return;
                        System.out.println(Thread.currentThread().getName() + "-" + count++);
                    }, "t" + (i + 1));
                } catch (InterruptedException e) {
                    return;
                }

            }
        }
    }

    public static void main(String[] args) {
        int threadCount = 3;
        new ThreadJoinDemo(threadCount).start();
    }

}
